package com.wwwc.index.web.servlet;

import java.io.*;
import java.awt.*;
import java.text.*;
import java.util.*;
import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.ServletRequestWrapper;
import java.net.*;

import javax.ejb.*;
import javax.naming.*;
import java.rmi.*;
import javax.rmi.*;

import com.wwwc.util.web.*;
import com.wwwc.index.web.ejb.database.*;

public class ShowAdv {
    private EJBDatabaseQuery ejbdb;

    public StringBuffer getAdv (String sid, String position) {
	StringBuffer sbf = new StringBuffer();

	if(ejbdb == null) {
	    ejbdb = (new DatabaseEJBQuery()).getEJBDatabaseQuery();
	}

	try {
	    long ct = System.currentTimeMillis();
	    String query = "SELECT * FROM ADS WHERE START_TIME <"+ ct +" AND END_TIME>"+ct+" AND SID='"+sid+
		"' AND POSITION="+ position+";";
	    
	    ArrayList a = ejbdb.selectSingleRecord(query);
	    sbf = new StringBuffer();
	    
	    if(a != null && a.size()>3) {
		updateAdPageCounter(""+a.get(0));
		sbf.append("\n<FORM method='post' action='t' target='_blank'>");
		sbf.append("\n<TABLE><TR><TD align='center' valign='top'>");	
		sbf.append("\n<input type=image src="+a.get(2)+" border=0>");

		sbf.append("\n</TD></TR></TABLE>");
		sbf.append("\n<input type=hidden name=adv_id value="+a.get(0)+">");
		sbf.append("\n<input type=hidden name=adv_url value="+a.get(3)+">");
		sbf.append("\n<input type=hidden name=adv_sid value='"+sid+"'>");
		sbf.append("\n<input type=hidden name=adv_position value="+a.get(6)+">");
		sbf.append("\n<input type=hidden name=tid value='adv'>");
		sbf.append("\n</FORM>");
	    }
	    else {
		sbf.append("\n<FORM method=post action=i>");
		sbf.append("\n<TABLE><TR><TD>");	 
		sbf.append("\n<input type=image src=/images/adv/default"+position+".gif border=0>");
		sbf.append("\n</TD></TR></TABLE>");
		sbf.append("\n<input type=hidden name=adv_url value=''>");
		sbf.append("\n<input type=hidden name=adv_sid value='"+sid+"'>");
		sbf.append("\n<input type=hidden name=adv_position value='"+position+"'>");
		sbf.append("\n<input type=hidden name=mid value='adv'>");
		sbf.append("\n</FORM>");
	    }
	}
	catch(IOException e) {
	}
	
	return sbf;
    }

    public boolean updateAdPageCounter (String adv_id) {
	if(ejbdb == null) {
	    ejbdb = (new DatabaseEJBQuery()).getEJBDatabaseQuery();
	}

	try {
	    String query = "SELECT PAGE_COUNTER FROM ADS WHERE ID="+adv_id+";";
	    String temp = ejbdb.selectSingleFieldValue(query, "PAGE_COUNTER");
	    int count = 1;
	    if(temp != null && temp.length()>0) {
		count = Integer.parseInt(temp);
	    }
	    
	    query = "UPDATE ADS SET PAGE_COUNTER="+(count+1)+" WHERE ID="+adv_id+";";
	    ejbdb.update(query);
	}
	catch(IOException e) {
	    System.out.println("ContentDisplayBean:updateAdPageCounter:Error:"+e);
	}
	return true;
    }
}
